<template>
	<div :class="isHistory?'is-history':''">
		
		<!--<detailCard v-if="cardData" :data="cardData" icon-class="icon-yunzhuji"></detailCard>-->
		<bianpaiDetail 
			v-show="cardData"
			ref="bianpaiDetail"
			></bianpaiDetail>
		
		<div class="app-joint-box"> 
			<!--<div style="position: fixed;left:0 ;top: 90%; width: 200px;background: #000;height: 100%;overflow: scroll;">
				<button @click="outPutDatas">outPutDatas</button>
				<div style="color: #fff;">
					{{data}}
				</div>
			</div>-->
			
			<!--<div class="deployConfigSet">
				<div class=""></div>
			</div>-->
			
			<div v-if="viewTemplateData" class="view-template-data">
				<el-form  label-width="100px" class="demo-ruleForm">
					<el-form-item label="模板名称：" >
						{{viewTemplateData.name}}
					</el-form-item>
					<el-form-item label="应用版本：" >
						{{viewTemplateData.appVersion}}
					</el-form-item>
					<el-form-item label="部署类型："  >
						<div v-html="deployTypeFilter(viewTemplateData.deployType,viewTemplateData.templateType)"></div>
					</el-form-item>
					<el-form-item label="应用类型：" >
						{{viewTemplateData.appType}}
					</el-form-item>
					<el-form-item label="部署模式：" >
						<div v-html="deployModelFilter(viewTemplateData.deployModel)"></div>
					</el-form-item>
					<el-form-item label="创建者："  >
						{{viewTemplateData.creator}}
					</el-form-item>
					<el-form-item label="创建时间：" >
						{{viewTemplateData.createTime}}
					</el-form-item>
				</el-form>
				
			</div>
			
			<div class="joint-box-select" v-if="!isHistory">
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="模板类型：" >
				    <mobanTypeSelect :disabled="disabledViewEdit" @change="changeMbType"></mobanTypeSelect>
				  </el-form-item>
				  <el-form-item label="应用类型：" >
				    <baseSelect 
				    	:disabled="disabledViewEdit"
							ref="appTypeSelect"
							:optionList="appTypeOptions" 
							@change="appTypeChange"></baseSelect>
				  </el-form-item>
					<el-form-item label="编排名称：" prop="name">
				    <el-input :disabled="!disabledViewEdit&&!!id" v-model="ruleForm.name"></el-input>
				  </el-form-item>
				  <el-form-item style="background: none;box-shadow: none;" label="" prop="">
				    <el-button :disabled="btnLoading" v-if="!disabledViewEdit&&!id" type="primary" @click="creatDatas()">创建</el-button>
				    <el-button :disabled="btnLoading" v-if="id&&!disabledViewEdit" type="primary" @click="saveDatas()">保存</el-button>
				    <el-button :disabled="btnLoading" v-if="isDeploy" type="primary" @click="btnLoading=true;deployDatas()">发布</el-button>
				    <el-button :disabled="btnLoading" @click="back">取消</el-button>
				  </el-form-item>
				</el-form>
				
			</div>
			
			<!-- Page Contents -->
	    <div class="pusher" >
	        <div class="article">
	            <div class="main ui container">
	                <div class="ui centered grid">
	                    <div class="twelve wide column">
	                        <div class="ui segment paper-container">
	                            <div id="paper"></div>
	                            <div class="ui right dividing rail">
	                                <div class="ui header" id="inspector-heading">
	                                </div>
	                                <div class="inspector-container"></div>
	                            </div>
	                            <div :class="'ui left dividing rail ' + (leftTempList?'show':'') ">
	                                <div class="stencil-container ">
	                                	<span class="grey" v-if="mbType" style="padding: 10px;font-size: 12px;">
	                                		
	                                	</span>
	                                	<span class="grey" v-else style="padding: 10px;font-size: 12px;">
	                                		请选择模板类型
	                                	</span>
	                                </div>
	                            </div>
	                        </div>
	                    </div>
	                </div>
	            </div>
	        </div>
	    </div>
	
	    <!--<div class="ui mini modal">
	        <div class="header">
	            Double Click Event
	        </div>
	        <div class="content">
	            <p>This Event is attached to double click! When an element is clicked, this event is triggered. See console to view clicked element attributes.</p>
	        </div>
	        <div class="actions">
	            <div class="ui positive right labeled icon button">
	                OK
	                <i class="checkmark icon"></i>
	            </div>
	        </div>
	    </div>-->
	    
	    
			<deployConfigDialog
				ref="deployConfigDialog"
				@close="saveDeployConfig"
				></deployConfigDialog>
			
			
			<!--<shiliListDialog
				@refresh="refresh"
				v-if="isHistory"
				ref="shiliListDialog"
				></shiliListDialog>-->
		
		</div>
	</div>
</template>




<script>
import baseSelect from "@/view/components/select/select";
import mobanTypeSelect from "./mobanTypeSelect";
import deployConfigDialog from "./deployConfigDialog";
import bianpaiDetail from "./bianpaiDetail";

import shiliListDialog from "./shiliListDialog";
import {getTemplateType} from "@/service/swagger/TemplateControoler";
import {create,update,getOrchestrateTemplate,orchestrate,getInstHistory} from "@/service/swagger/OrchestrateController";
import detailCard from "@/view/components/card/detailCard";
import {bianpaiStatusFilter,deployTypeFilter,deployModelFilter} from "@/filters/status/index";
import {listenner} from "@/utils/statuslistener" ;
import {getTemplateById} from'@/service/swagger/AcTemplateController';

require("@/libs/joint/assets/libraries/jquery.min.js");
require("@/libs/joint/assets/libraries/lodash.min.js");
require("@/libs/joint/assets/libraries/backbone.min.js");
require("@/libs/joint/assets/semantic/semantic.min.js");
require("@/libs/joint/assets/rappid/rappid.min.js");
window.App = {};
require("@/libs/joint/app/sample-graph.js");
require("@/libs/joint/app/stencils.js");
require("@/libs/joint/app/data-source-stencils.js");
require("@/libs/joint/app/inspector.js");
require("@/libs/joint/app/selection.js");
require("@/libs/joint/index.js");
require("@/libs/joint/app/models/joint.shapes.app.js");


export default {
	components: {
		baseSelect,
		mobanTypeSelect,
		deployConfigDialog,
		shiliListDialog,
		detailCard,
		bianpaiDetail
	},
	data() {
		return {
			deployTypeFilter : deployTypeFilter,
			deployModelFilter : deployModelFilter ,
			
			btnLoading : false,
			id : this.$route.query.id,
			instId : this.$route.query.instId,
			updateId : "",
			
			isDeploy :  this.$route.query.isDeploy,
			isHistory :  this.$route.query.isHistory,
			disabledViewEdit : this.$route.query.isDeploy || this.$route.query.isHistory ,
			
			serviceSourceArr : {}, // 部署配置存储
			viewTemplateData : null,
			ruleForm :{
				name : "",
			},
			rules : {
				name :[{ required: true, message: ' ', trigger: 'blur' },]
			},
			mbType : "",
			leftTempList : null,
			app : null,
			data : [], // view 视图 data
			
			cardData : null,
			appTypeOptions : [],
		}
	},
	mounted(){
		this.initPage();
	},
	methods: {
		back(){
			this.$router.push({
				path : "/bp/yy",
				query:{}
			})
		},
		goHistory(){
			this.$router.push({
				path : "/bp/gz",
				query:{}
			})
		},
		refresh(){
			this.initPage();
		},
		initPage(){
			if(this.instId){
				// 实例详情 查看部署
				getInstHistory({
					id:this.instId,
				}).then(ret=>{
					if(!ret.code){
						
						this.data = JSON.parse(ret.data.viewText) ;
						//this.shiliLists = ret.data.templateInsts ;
						this.initTool();
						
						this.cardData = {
							"发布名称" : ret.data.name ,
							"总实例数" : ret.data.total ,
							"状态" : {html : bianpaiStatusFilter(ret.data.status)},
							"异常实例数" : ret.data.abnormal ,
							"编排名称" : ret.data.templateName ,
							"正常实例数" : ret.data.normal ,
							"未部署实例数" : ret.data.giveUp ,
						};
						
						this.$refs.bianpaiDetail.initData(ret.data , ret.data )
						
					}
				})
			}
			else if(this.id){
				// 部署模板 || 查看详情
				getOrchestrateTemplate({
					id : this.id
				}).then(ret=>{
					if(!ret.code&&ret.data){
						this.data = JSON.parse(ret.data.viewText) ;
						if(ret.data.dependsTree){
							for(let i in JSON.parse(ret.data.dependsTree)){
								this.serviceSourceArr[i] = null;
							}
						}
						if(!this.isDeploy){
							this.ruleForm.name = ret.data.name ;
						}
						this.updateId = ret.data.id ;
						this.initTool();
						this.serviceTemplateId = ret.data.serviceTemplateId;
					}
				})
			}else{
				// 创建
				this.initTool();
			}
		},
		
		initTool() {
			setTimeout(()=>{
				joint.setTheme('modern');
				this.app = new App.MainView({ el: '#app' });
				// app.graph.fromJSON(JSON.parse(App.config.sampleGraphs.emergencyProcedure));
				this.app.graph.fromJSON({cells : this.data || [] });
				// console.log(55,this.app )
				
				// add click 
				this.app.paper.on('element:pointerup link:options', (cellView) => {
					
					//console.log(cellView)
					if(cellView&&cellView.model&&cellView.model.attributes&&cellView.model.attributes.sourceData){
						this.openDataView(cellView.model.attributes.sourceData)
					}else{
						this.openDataView(null)
					}
				})
			},200)
			
		},
		openDataView(data){
			console.log("模板详情：", data)
			if(!data){
				this.viewTemplateData = null ;
				return ;
			}
			if(this.disabledViewEdit){
				if(this.isDeploy){
					// 修改部署配置
					const formData = this.serviceSourceArr[data.templateId];
					if(formData){
						this.$refs.deployConfigDialog.open().initData(data , formData.data ,true , true );
					}else{
						getTemplateById(data.templateId).then(ret=>{
	              if(!ret.code&&ret.data){
	              	this.$refs.deployConfigDialog.open().initData(data , ret.data ,false ,true);
	              }
	          })
					}
				}else if(this.isHistory){
					this.viewTemplateData = data;
//					this.$refs.shiliListDialog.open().initData({
//						serviceTemplateId : this.id,
//						templateId : data.templateId ,
//						serviceInstId : this.instId ,
//					})
				}
			}else{
				// 展示详情
				this.viewTemplateData = data;
			}
		},
		
		saveDeployConfig(name,data,validated){
			console.log("saveDeployConfig",{...data},validated)
			this.serviceSourceArr[data.templateId] = {
				data : data ,
				validated : validated,
			};
		},
		
		outPutDatas(){
			// 
			// console.log(66,joint)
			joint.storage.Local.insert('graphs', this.app.graph)
			joint.storage.Local.find('graphs', {}, (err, graphs)=>{
				//console.log(77,err,graphs)
				if(graphs&&graphs.length){
					this.data = graphs[graphs.length-1].cells
				}
			}); 
		},
		
		creatDatas(){
			// 创建 编排
			this.outPutDatas();
			this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.saveForm(create);
        } else {
          return false;
        }
      });
		},
		
		saveDatas(){
			// 保存对应用编排的 修改
			this.outPutDatas();
			this.saveForm(update,{
				id: this.updateId
			});
		},
		
		deployDatas(){
			// 部署应用编排
			let hasUnfinishSet ;
			let serviceArr = []
			for (let [key, value] of Object.entries(this.serviceSourceArr)) {
			  if(!value){
			  	hasUnfinishSet = true ;
			  }else if(!value.validated){
			  	hasUnfinishSet = value.data.name
			  }else{
			  	let data = value.data ;
			  	serviceArr.push({
						appName : data.appName  ,
						clusterId : data.clusterId,
						clusterName : data.clusterName  ,
						deployInstCounts : data.deployInstCounts  ,
						deployModel : data.deployModel  ,
						spec : data.varsInfoShili[0].varsValue || ""  ,
						envs : data.varsInfoEnv.map(el=>{
							return {
								name : el.varsName ,
								value : el.varsValue ,
							}
						})  ,
						instConfigs : data.templateConfigs.map(el=>{
							return {
								configName : el.configName ,
								configParentPath : el.configParentPath,
								configSourceFile : el.configSourceFile,
								// instId : el.varsValue ,
								usedMethod : el.usedMethod ,
							}
						})  ,
						ips : data.ips  ,
						logVolumes :  data.varsInfoLog.map(el=>{
							return {
								logPath : el.varsValue ,
							}
						}) ,
						portMappings :  data.varsInfoPort.map(el=>{
							return {
								dockerPort : el.varsName ,
								vmPort : el.varsValue ,
							}
						})    ,
						templateId : data.templateId  ,
						volumes : data.varsInfoVolume.map(el=>{
							return {
								dockerPath : el.varsValue ,
							}
						}) ,
			  	})
			  }
			}
			if(hasUnfinishSet){
				this.btnLoading = false;
				this.$message({showClose: true,message: (typeof(hasUnfinishSet)!="string"?'有模板未设置完成':'模板' + hasUnfinishSet + "设置验证失败") + '！请点击模板进行部署设置',type: 'error'});
				return ;
			}
			
			
			this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 可以部署
					orchestrate({
						name : this.ruleForm.name,
						serviceTemplateId : this.serviceTemplateId ,
						services : serviceArr ,
					}).then(ret=>{
						this.btnLoading = false;
						if(!ret.code){
							this.goHistory();
						}
					})
					
        } else {
        	this.btnLoading = false;
          return false;
        }
      });
			
		},
		
		saveForm(fn,params){
				this.$confirm("是否保存应用编排？", "提示", {
	            confirmButtonText: "确定",
	            cancelButtonText: "取消",
	          })
	        .then(() => {
	        	
	          fn({
	          	...params ,
							name : this.ruleForm.name ,
							items : this.getDataItems(this.data),
							remark : "",
							viewText : JSON.stringify(this.data) ,
						}).then(ret=>{
							this.btnLoading = false;
							if(!ret.code){
								this.$message({showClose: true,message: '创建成功！',type: 'success'});
								this.back();
							}
						});
	      })
		},
		
		changeMbType(namv,v,arr){
			console.log("切换模板类型：",namv,v,arr)
			if(arr[0]&&arr[0].sourceData){
				this.mbType = arr[0].label
			}else{
				this.mbType = "";
			}
			switch(this.mbType){
				case "容器" : case "裸应用" : case "组件" :  
					getTemplateType(arr[0].sourceData).then(ret=>{
						if(!ret.code&&ret.data){
							this.addTemplateStencil(ret.data)
						}
					})
				; break;
				default :
					this.addTemplateStencil([])
				;break;
			}
			this.leftTempList = null;
		},
		
		appTypeChange(name , v, selectedArr){
			console.log("切换应用类型：",name , v, selectedArr)
			if(v){
				this.leftTempList = v ;
				this.app.stencil.load({
					temp : selectedArr[0].sourceData // : templataArr
				});
			}
		},
		
		addTemplateStencil(datas){
			let hash = {}
			datas.forEach(el=>{
				if(!hash[el.appType]){
					hash[el.appType] = [];
				}
				hash[el.appType].push({
						sourceData : el,
						templateId : el.templateId,
             type: 'basic.Rect',
             size: { width: 5, height: 3 },
             attrs: {
                 '.': {
                     'data-tooltip': 'Rectangle',
                     'data-tooltip-position': 'left',
                     'data-tooltip-position-selector': '.joint-stencil'
                 },
                 rect: {
                     rx: 5,
                     ry: 5,
                     width: 100,
                     height: 50,
                     fill: '#fff',
                     stroke: '#0f427f',
                     'stroke-width': 1,
                     'stroke-dasharray': '0'
                 },
                 text: {
                     text: el.name || '未名称',
                     fill: '#0f427f',
                     'font-family': 'Roboto Condensed',
                     'font-weight': 'Normal',
                     'font-size': 11,
                     'stroke-width': 0
                 }
            }
         })
			})
			let newOptions = [];
			for(let i in hash ){
				newOptions.push({
					label : i ,
					value : i ,
					sourceData : hash[i],
				})
			}
			this.$refs.appTypeSelect.asyncUpdateOption(newOptions)
		},
		
		
		getDataItems(data){
			// 梳理模板间逻辑关系
			
			/*
			  * 
			
			{
	      "appType": "string",
	      "depends": [
	        {
	          "relaType": "string",
	          "templateId": "string"
	        }
	      ],
	      "templateId": "string",
	      "version": "string"
	    }
	    
    */
   		let items = {};
   		let arows = [];
   		data.forEach(el=>{
   			if(el.type=="app.Link"){ // 是箭头
   				arows.push(el)
   			}
   			else if(el.type=="basic.Rect"){
   				items[el.id] = {
   					appType : el.sourceData.appType || "" ,
   					depends : [],
   					templateId : el.sourceData.templateId,
   					version : el.sourceData.appVersion 
   				}
   			}else{
   				console.log("未识别的逻辑：" , el)
   			}
   		})
   		arows.forEach(el=>{
   			const sourceId = el.source.id;
   			const targetId = el.target.id;
   			const relaValue = el.attrs&&el.attrs[".connection"]?el.attrs[".connection"].strokeDasharray : "0" ;
   			const _relaType = {
   				"0" :"depend" ,
   				"10,5" :"relation" 
   			}
   			items[sourceId].depends.push({
   				relaType : _relaType[relaValue],
   				templateId : items[targetId].templateId ,
   			})
   		})
   		
			return Object.values(items);
		}
		
	}
}
</script>

<style lang="scss">
	@import "../../../../styles/variables.scss";
	
	@import "../../../../libs/joint/assets/semantic/semantic.min.css";
	@import "../../../../libs/joint/assets/rappid/rappid.min.css";
	@import "../../../../libs/joint/assets/css/material.css";
	@import "../../../../libs/joint/assets/css/style.css";
	
	.app-main-content {
		height: calc(100% - 110px);
	}
	.app-joint-box {
		overflow: hidden;
		position: relative;
		margin-bottom: -21px;
		
		& > .pusher > .article {
			margin: 0;
			
			& > .main {
				width: 100%;
				margin: 0 !important;
				
				& > div {
					margin: 0;
					width: 100%;
					
					& > .twelve {
						padding: 0;
						width:100% !important;
						
						& > .segment  {
							border: 0;
							height: calc(100vh - 200px) !important;
						}
					}
				}
			}
		}
		
		.twelve .left {
			z-index: -55;
			left: 10px;
			top: 73px !important;
			right: auto;
			
			&.show {
				z-index: 2;
			}
			.groups-toggle,.search-wrap {
				display: none;
			}
			
			.content {
				margin: 2px 0;
				padding: 0;
				top: 0px !important;
			}
			
			.joint-stencil.joint-theme-modern {
				background: none;
			}
			
			.elements.joint-paper.joint-theme-modern {
				width: 100% !important;
			}
			
			.group-label {
				display: none;
				margin: 0 0 -10px 0 !important;
				background: #fff;
				font-size: 14px;
				font-weight: normal;
				color: #333;
				
				&:hover {
					color: #666;
				}
				&:before {
					display: none;
				}
			}
		}
		.twelve #paper {
			.joint-paper.joint-theme-modern {
				box-shadow: none;
			}
			.joint-paper-scroller {
				background: #f4f5f8 !important;
			}
			.joint-paper-grid { 
				background: #f4f5f8;
				background-image:
				linear-gradient(white 1px, transparent 0),
				linear-gradient(90deg, white 1px, transparent 0) !important;
				background-size: 10px 10px;
			}
		}
		.twelve .right {
			overflow: visible !important;
			right: 10px;
			background: none !important;
			box-shadow: none !important;
			left: auto;
			
			.header {
				display: none;
			}
			.joint-inspector {
				overflow: visible;
				top: 10px;
				background: none;
				
				label {
					color: #333;
				}
			}
			.group {
				background: #fff !important;
				box-shadow: 0 0 5px 0 rgba(0,0,0,.3);
				border-radius:5px ;
				
				.group-label {
					display: none;
				}
				
				.select-box-option-content {
					color: #333;
				}
			}
		}
		.twelve {
			& .left,& .right {
				background: #fff;
				width: 220px;
				border: 0 !important;
				border-radius:5px ;
				overflow: hidden;
				top: 10px;
				bottom: 10px;
				height: auto;
				box-shadow: 0 0 5px 0 rgba(0,0,0,.3);
				
				.joint-paper {
					background: #fff !important;
				}
			}
			
			& .right {
				top: 0;
			}
		}
		
		
		
		.joint-box-select {
			position: absolute;
			left: 10px;
			top: 10px;
			z-index: 5;
			.el-select {
				width: 115px !important;
			}
			
			div {
				display: inline-block;
			}
			
			.el-form-item {
				margin-right: 8px;
				background: #fff;
				padding: 10px;
				box-shadow: 0 0 5px 0 rgba(0,0,0,.3);
				font-size: 12px;
				line-height: 32px;
				height: 30px;
				white-space: nowrap;
				border-radius:5px ;
			}
			.el-form-item__content {
				
				margin-left: 0 !important;
			}
		}
		
		.view-template-data {
			overflow: auto;
			height: auto;
			width: 260px;
			position: absolute;
			right: 25px;
			top: 10px;
			bottom:10px;
			background: #fff;
			border-radius:5px ;
			padding: 10px 0;
			box-shadow: 0 0 5px 0 rgba(0,0,0,.3);
			z-index: 66;
			line-height: 1.5;
			
			
			.el-form-item {
				margin-bottom: 0;
			}
			
			.el-form-item__label {
				font-size: 12px;
				color: #999;
			}
			
			.el-form-item__content {
				font-size: 12px;
				color: #333;
			}
			
		}
		
	}
	
	.select-box-selection {
		border: 1px solid #ddd !important;
		padding: 0 15px !important;
		height: 30px !important;
		font-size: 12px !important;
		line-height: 30px !important;
		border-radius: 3px;
	}
	
	.joint-select-box-options {
		width: 224px !important;
		margin-top: 31px;
		border : 1px solid #ddd !important;
		background: #fff !important;
		color: #333 !important;
		
		.select-box-option-content {
			padding: 0 15px !important;
			height: 30px;
			line-height: 30px;
			&:hover {
				background: #f5f7fa !important;
			}
			&.selected {
				font-weight: bold !important;
				background: #fff !important;
				color: $mainBlue;
				&:after {
					display: none !important;
				}
			}
		}
	}
	
	.handle {
		&.fork,&.clone{
			display:none;
		}
	}
	
	.joint-paper-scroller {
		overflow: hidden !important;
	}
	
	
	.is-history {
		
		.marker-arrowhead,.connection-wrap,.tool-options,.tool-remove {
			display: none;
		}
		
	}
	
</style>

